Projects = Ext.extend(Ext.Panel, {
    initComponent: function() {
        //this.title = '';
        this.region = 'center';
        this.layout = 'border';
        this.margins = '0 0 0 0';
        this.border = false;
        this.autoScroll = true;

        this.nfs = false;

        this.prjDetailPanelH = parseInt(getCookie('prjDetailPanelH'));
        this.prjDetailPanelH =(this.prjDetailPanelH) ? this.prjDetailPanelH : 500;

        this.initDataStores();
        this.initClientBrandGrid();
        this.initProjectsGrid();
        this.initProjectDetail();
        this.initEditWin();

        this.items =  [ this.clientBrandGrid, this.projectsGrid, this.projectDetail ];

        Projects.superclass.initComponent.call(this);

    },
    initDataStores: function() {
        this.projectsStore = new Ext.data.GroupingStore({
            reader: new Ext.data.JsonReader({
                root: 'data',
                fields: [
                    {type: 'int', name: "project_id"}, {type: 'int', name: 'sheme_type_id'}, {type: 'date', name: 'start_date'}, {type: 'date', name: 'finish_date'},
                    {type: 'int', name: 'action_id'},{type: 'int', name: 'media_type_id'}, {type: 'int', name: 'ba_id'},
                    {type: 'int', name: 'ma_id'},{type: 'int', name: 'ma_b_id'}, {type: 'int', name: 'smi_id'}, {type: 'int', name: 'smi_b_id'},
                    {type: 'int', name: 'contract_1_id'}, {type: 'int', name: 'contract_2_id'}, {type: 'int', name: 'contract_3_id'},
                    {type: 'float', name: 'transfer_costs'}, {type: 'float', name: 'additional_costs'}, {type: 'float', name: 'gross_profit'},
                    {type: 'float', name: 'effectiveness'}
               ]
            }),
            url: 'main?action=GetProjects',
            autoDestroy: true,
            groupField:'action_id',
            listeners:{ scope: this,
                load: function() { this.projectsGrid.selModel.selectRow( this.projectsGrid.curRecIdx ); }
            }
        });
    },
    initClientBrandGrid: function() {
        this.clientBrandGrid = new Ext.grid.GridPanel({
            title: 'Клиенты',
            region: 'west',
            width: 250,
            //split: true,
            height: 800,
            frame: false,
            curRecIdx: 0,
            store: brendsStore,
            margins:'0 3 0 0',
            cmargins:'0 3 0 0',
            colModel: new Ext.grid.ColumnModel({
                defaults: {
                    width: 170,
                    sortable: true
                },
                columns: [
                    {header: 'Рекламодатель', width: 150, dataIndex: 'client_id', hidden: true, renderer:renderActors},
                    {header: 'Брэнд', dataIndex: 'brand_id', renderer:renderBrand }
                ]
            }),
            view: new Ext.grid.GroupingView({
                forceFit: true,
                showGroupName: true,
                enableNoGroups: true,
                enableGroupingMenu: false,
                hideGroupedColumn: true,
                groupTextTpl: '&nbsp;&nbsp;&nbsp;{text}'
            }),
            sm: new Ext.grid.RowSelectionModel({
                singleSelect:true,
                listeners: { scope: this,
                    rowselect: function(sm, row, rec) {
                        var act_id = rec.data.action_id;
                        this.projectsStore.baseParams = {action_id: act_id };
                        this.projectsStore.load();
                    }
                }
            })
        });
    },
    initProjectsGrid: function() {
        this.projectsGrid = new Ext.grid.GridPanel({
            title: 'Проекты',
            region: 'center',
            //split: true,
            height: 800,
            frame: false,
            curRecIdx: 0,
            store: this.projectsStore,
            margins:'0 0 0 0',
            cmargins:'0 0 0 0',
            colModel: new Ext.grid.ColumnModel({
                defaults: {
                    width: 170,
                    sortable: true
                },
                columns: [
                    {header: 'ID', width: 40, dataIndex: 'project_id', hidden: true},
                    {header: 'Акция', dataIndex: 'action_id', renderer:renderAction },
                    {header: 'Медиа', width: 80, dataIndex: 'media_type_id', renderer:renderMedia},
                    {header: 'Схема', width: 30, dataIndex: 'sheme_type_id', renderer: renderShem },
                    {header: 'Медиа агентство', width: 60, dataIndex: 'ma_id', renderer: renderActors },
                    {header: 'МA Бенефициар', width: 60, dataIndex: 'ma_b_id', renderer: renderActors },
                    {header: 'Баинговое агентство', width: 60, dataIndex: 'ba_id', renderer: renderActors },
                    {header: 'СМИ', width: 60, dataIndex: 'smi_id', renderer: renderActors },
                    {header: 'СМИ Бенефициар', width: 60, dataIndex: 'smi_b_id', renderer: renderActors },
                    {header: 'Бюджет клиента', width: 60, dataIndex: 'budj_c', align: 'right'},
                    {header: 'Бюджет СМИ', width: 60, dataIndex: 'budj_s', align: 'right'},
                    {header: 'Валовая прибыль', width: 60, dataIndex: 'gross_profit', align: 'right', renderer: valPofit },
                    {header: 'Трансферные расходы', width: 60, dataIndex: 'transfer_costs', align: 'right'},
                    {header: 'Дополнительные расходы', width: 60, dataIndex: 'additional_costs', align: 'right'},
                    {header: 'Рентабильность', dataIndex: 'effectiveness', hidden: true}
                ]
            }),
            view: new Ext.grid.GroupingView({
                forceFit: true,
                showGroupName: true,
                enableNoGroups: true,
                enableGroupingMenu: false,
                hideGroupedColumn: true,
                groupTextTpl: '&nbsp;&nbsp;&nbsp;{text}'
            }),
            sm: new Ext.grid.RowSelectionModel({
                singleSelect:true,
                listeners: { scope: this,
                    rowselect: function(sm, row, rec) {
                        if(this.projectsGrid.curRecIdx == row && this.nfs) return false;
                        //this.nfs = true;
                        this.projectsGrid.curRecIdx = row;
                        this.Contracts.removeAll(true);
                        if(rec.data.sheme_type_id == 1) {
                            var KM = new ContractDetail(); KM.title = 'Клиент - Медиа Агенство';
                            var MB = new ContractDetail(); MB.title = 'Медиа агенство - Баинговое Агенство';
                            var BS = new ContractDetail(); BS.title = 'Баинговое агентство - СМИ';
                            KM.cnt_id = rec.data.contract_1_id; KM.getContractDetail(); this.Contracts.add(KM);
                            MB.cnt_id = rec.data.contract_2_id; MB.getContractDetail(); this.Contracts.add(MB);
                            BS.cnt_id = rec.data.contract_3_id; BS.getContractDetail(); this.Contracts.add(BS);
                        }
                        if(rec.data.sheme_type_id == 2) {
                            var KM = new ContractDetail(); KM.title = 'Клиент - Медиа Агенство';
                            var MS = new ContractDetail(); MS.title = 'Медиа агенство - СМИ';
                            KM.cnt_id = rec.data.contract_1_id; KM.getContractDetail(); this.Contracts.add(KM);
                            MS.cnt_id = rec.data.contract_3_id; MS.getContractDetail(); this.Contracts.add(MS);
                        }
                        if(rec.data.sheme_type_id == 3) {
                            var BS = new ContractDetail(); BS.title = 'Баинговое агентство - СМИ';
                            var KB = new ContractDetail(); KB.title = 'Клиент - Баинговое агенство';
                            KB.cnt_id = rec.data.contract_1_id; KB.getContractDetail(); this.Contracts.add(KB);
                            BS.cnt_id = rec.data.contract_3_id; BS.getContractDetail(); this.Contracts.add(BS);
                        }
                        this.Contracts.setActiveTab(0);
                    }
                }
            }),
            tbar: [
                { icon: '/bres/img/butt_ico_16/note-add-icon.png', text: 'Добавить', handler: this.addProject },'-',
                { icon: '/bres/img/butt_ico_16/note-edit-icon.png', text: 'Редактировать', handler: this.eddProject },'-',
                { icon: '/bres/img/butt_ico_16/note-remove-icon.png', text: 'Удалить', handler: this.delProject }
            ]
        });
	this.projectsGrid.on('click', function() {
            clearToolbarActions();
            attachToolbarNav(this);
            //selectGrid(this);
            setToolbarActionHandler('addrec', toolbarHandlerFactory('addrec', this));
            if(this.selModel.getSelected()) {
                setToolbarActionHandler('editrec', toolbarHandlerFactory('editrec', this));
                setToolbarActionHandler('deleterec', toolbarHandlerFactory('deleterec', this));
            }
        });
	this.projectsGrid.on('rowcontextmenu', function(grid, idx, evObj) {
            grid.selModel.selectRow(idx);
            grid.fireEvent('click');
            popUpMenu.showAt(evObj.getXY());
            evObj.stopEvent();
        }, this);
	this.projectsGrid.on('containercontextmenu', function(gr, evObj) {
            gr.fireEvent('click');
            popUpMenu.showAt(evObj.getXY());
            evObj.stopEvent();
        }, this);
        this.projectsGrid.on('refresh', function() { this.projectsStore.load(); });
        this.projectsGrid.on('addrec', this.addProject );
        this.projectsGrid.on('editrec', this.eddProject );
        this.projectsGrid.on('deleterec', this.delProject );
    },
    initProjectDetail: function() {
        this.Contracts = new Ext.TabPanel({
            region: 'center',
            title: 'Детализация проекта',
            margins:'5 3 3 3',
            cmargins:'5 3 3 3',
            border: false,
            items: [ {} ]
        });
        this.projectDetail = new Ext.Panel({
            region: 'south',
            title: 'Детализация проекта',
            layout: 'border',
            margins:'0 0 0 0',
            cmargins:'0 0 0 0',
            split: true,
            height:this.prjDetailPanelH,
            frame: false,
            border: true,
            items: [  this.Contracts ]
        });
        this.projectDetail.on('resize', function() {
          setCookie('prjDetailPanelH', this.getHeight());
        }, this.projectDetail);
    },
    initEditWin: function() {
        this.EditWin = new ProjectEditWin();
    },
    addProject: function() { this.EditWin.editRec = {}; this.EditWin.showWin('add'); },
    eddProject: function() { this.EditWin.editRec = this.projectsGrid.getSelectionModel().getSelected(); this.EditWin.showWin('edit'); },
    delProject: function() {
            var rec = this.projectsGrid.getSelectionModel().getSelected();
            if(rec) {
                    Ext.MessageBox.confirm('Внимание !!!', 'Вы действительно хотите удалить эту запись и все связаные с ней  объекты?',
            function(btn) {
                if (btn == 'yes'){
                    var Project_id = rec.data.id;
                                            Ext.Ajax.request({
                                                    url: 'main?action=deleteProject',
                                                    params: { id: Project_id },
                                                    scope: this,
                                                    callback: function(options, success, response) {
                                                            var ansv = Ext.decode(response.responseText);
                                                            if(ansv.sucsess === true) {
                                                                    this.projectsStore.load();
                                                            } else { error_mes('Ошибка',  ansv.error); }
                                                    }
                                            });
                }
            }, this
        );
            } else error_mes('Внимание!!!', 'Вы не выбрали запись для удаления.');
    }
});


